import React, { useState } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { AiOutlineLoading3Quarters } from 'react-icons/ai'
import SvgIcon from '../SvgIcon'

const Switch = ({
  checked,
  checkedChildren,
  unCheckedChildren,
  disabled,
  loading,
  onChange,
  onClick,
  defaultChecked,
  ballWidth,
  loadingIcon,
  DEFAULT_MARGIN,
  ...rest
}) => {
  const [isChecked, setChecked] = useState(checked || defaultChecked)
  const onClickContiner = () => {
    onClick && onClick()

    if (checked || disabled || loading) return
    setChecked(state => !state)
    onChange && onChange()
  }

  const classString = classNames('inline-block rounded-full relative cursor-pointer select-none', {
    'h-6 min-w-12': true,
    'bg-blue-600': !!isChecked,
    'bg-gray-500': !isChecked,
    'bg-opacity-50 cursor-not-allowed': disabled || loading
  })

  const contentClass = classNames('transition-margin duration-200 my-0')
  const contentStyle = {
    marginLeft: isChecked ? DEFAULT_MARGIN : DEFAULT_MARGIN + ballWidth,
    marginRight: isChecked ? DEFAULT_MARGIN + ballWidth : DEFAULT_MARGIN
  }

  const ballClass = classNames('bg-white rounded-full absolute transition-all duration-200 ease-in-out')
  const ballStyle = {
    width: ballWidth,
    height: ballWidth,
    right: isChecked ? 2 : `calc(100% - ${ballWidth}px - 2px)`,
    top: 2
  }

  return (
    <div className={classString} onClick={onClickContiner} {...rest}>
      <div className={contentClass} style={contentStyle}>{isChecked ? checkedChildren : unCheckedChildren}</div>
      <div className={ballClass} style={ballStyle}>
        {loading && <SvgIcon spin center component={loadingIcon ?? <AiOutlineLoading3Quarters color='bg-blue-600' />} />}
      </div>
    </div >
  )
}

Switch.propTypes = {

}
Switch.defaultProps = {
  DEFAULT_MARGIN: 8,
  ballWidth: 20,
  defaultChecked: true,
}

export default Switch


{/* <AiOutlineLoading3Quarters color='red' /> */ }
{/* <SvgIcon spin center component={<AiOutlineLoading3Quarters color='red' />} /> */ }
{/* <SvgIcon spin center color='red' component={AiOutlineLoading3Quarters} />
<SvgIcon spin center color='red' component={(props) => <AiOutlineLoading3Quarters {...props}>} /> */}
// 想对AiOutlineLoading3Quarters的color进行劫持，对值进行字符串比对，设计几个默认color